<template>
  <el-dialog
    v-el-drag-dialog
    :title="!dataForm.newsId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="180px">
    <el-form-item label="新闻分类" prop="newsClassKey" v-if="dataForm.newsId == 0">
      <el-select v-model="dataForm.newsClassKey" placeholder="新闻分类">
        <el-option
          v-for="item in this.key"
          :key="item.newsClassKey"
          :label="item.classValue"
          :value="item.newsClassKey">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="咨询关键词(首页展示)" prop="keywords">
      <el-input v-model="dataForm.keywords" placeholder="咨询关键词(首页展示)"></el-input>
    </el-form-item>
    <el-form-item label="快乐咨询标题" prop="title">
      <el-input v-model="dataForm.title" placeholder="快乐咨询标题"></el-input>
    </el-form-item>
    <!-- <el-form-item label="咨询类型" v-if="dataForm.newsId === 0 && dataForm.newsClassKey !== ''">
      <el-radio v-model="dataForm.newType" label="1">普通咨询</el-radio>
      <el-radio v-model="dataForm.newType" label="2">视频咨询</el-radio>
    </el-form-item> -->
    <!-- <el-form-item label="列表文章标题图片" prop="titleImage" v-if="dataForm.newType === '1'|| dataForm.fileType === 1">
      <el-upload
      :action="this.$http.adornUrl(`/newInfo/uploadNewsInfo?token=${this.$cookie.get('token')}`)"
      :limit="1"
      list-type="picture-card"
      :file-list="dataForm.titleImage"
      :on-preview="handlePreview"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :on-exceed="onExceed">
      <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item> -->
    <el-form-item label="列表文章标题图片" prop="titleImage">
      <el-upload
        :class="{hide:hideUpload}"
        :action="this.$http.adornUrl(`/newInfo/uploadNewsInfo?token=${this.$cookie.get('token')}`)"
        :limit="1"
        list-type="picture-card"
        :file-list="dataForm.titleImage"
        :on-preview="handlePreview"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :on-exceed="onExceed">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <!-- <el-input v-model="dataForm.titleImage" placeholder="列表文章标题图片"></el-input> -->
    </el-form-item>
    <!-- <el-form-item label="视频文件" prop="video" v-if="dataForm.newType === '2' || dataForm.fileType === 2">
      <el-upload
        class="avatar-uploader"
        :action="this.$http.adornUrl(`/newInfo/uploadNewsInfoVideo?token=${this.$cookie.get('token')}&newsClassKey=${this.dataForm.newsClassKey}`)"
        accept='.mp4,.qlv,.qsv,.ogg,.flv,.avi,.wmv,.rmvb'
        :show-file-list="false"
        :before-upload="beforeUploadVideo"
        :on-success="handleVideoSuccess"
        :on-progress="uploadVideoProcess">
          <video
            v-if="this.dataForm.video !== '' && this.videoFlag === false"
            :src="this.dataForm.video"
            width="350"
            height="180"
            controls="controls">您的浏览器不支持视频播放</video>
          <i v-else-if="this.dataForm.video === '' && this.videoFlag === false" class="el-icon-plus avatar-uploader-icon"></i>
          <el-progress
            v-if="this.videoFlag === true"
            type="circle"
            :percentage="videoUploadPercent"
            style="margin-top:30px">
          </el-progress>
      </el-upload>
    </el-form-item> -->
    <el-form-item label="当前咨询来自哪个网站" prop="newsFrom">
      <el-input v-model="dataForm.newsFrom" placeholder="当前咨询来自哪个网站"></el-input>
    </el-form-item>
    <el-form-item label="点赞数量" prop="likeNumber" v-if="dataForm.newsId != 0">
      <el-input v-model="dataForm.likeNumber" placeholder="点赞数量"></el-input>
    </el-form-item>
    <el-form-item label="阅读数量" prop="readingNumber" v-if="dataForm.newsId != 0">
      <el-input v-model="dataForm.readingNumber" placeholder="阅读数量"></el-input>
    </el-form-item>
    <el-form-item label="转发数量" prop="forwardingNumber" v-if="dataForm.newsId != 0">
      <el-input v-model="dataForm.forwardingNumber" placeholder="转发数量"></el-input>
    </el-form-item>
    <el-form-item label="收藏数量" prop="collectionNumber" v-if="dataForm.newsId != 0">
      <el-input v-model="dataForm.collectionNumber" placeholder="收藏数量"></el-input>
    </el-form-item>
    <el-form-item label="评论数量" prop="commentsNumber" v-if="dataForm.newsId != 0">
      <el-input v-model="dataForm.commentsNumber" placeholder="评论数量"></el-input>
    </el-form-item>
    <el-form-item label="创建时间" prop="createTime" v-if="dataForm.newsId != 0">
      <el-input v-model="dataForm.createTime" placeholder="创建时间"></el-input>
    </el-form-item>
    <el-form-item label="创建快乐咨询时候的备注" prop="newsRemark">
      <el-input v-model="dataForm.newsRemark" placeholder="创建快乐咨询时候的备注"></el-input>
    </el-form-item>
    <el-form-item label="快乐咨询地址" prop="content">
      <el-input v-model="dataForm.content" placeholder="快乐咨询地址"></el-input>
    </el-form-item>
    <!-- <el-form-item label="视频文件" prop="video">
      <el-upload
        class="avatar-uploader"
        :action="this.$http.adornUrl(`/newInfo/uploadNewsInfoVideo?token=${this.$cookie.get('token')}&newsClassKey=${this.dataForm.newsClassKey}`)"
        accept='.mp4,.qlv,.qsv,.ogg,.flv,.avi,.wmv,.rmvb'
        :show-file-list="false"
        :before-upload="beforeUploadVideo"
        :on-success="handleVideoSuccess"
        :on-progress="uploadVideoProcess">
          <video
            v-if="this.dataForm.video !== '' && this.videoFlag === false"
            :src="this.dataForm.video"
            width="350"
            height="180"
            controls="controls">您的浏览器不支持视频播放</video>
          <i v-else-if="this.dataForm.video === '' && this.videoFlag === false" class="el-icon-plus avatar-uploader-icon"></i>
          <el-progress
            v-if="this.videoFlag === true"
            type="circle"
            :percentage="videoUploadPercent"
            style="margin-top:30px">
          </el-progress>
      </el-upload>
      <p>如果是视频咨询，请在这里上传视频资源，将地址复制到富文本链接中</p>
    </el-form-item> -->
    <el-form-item label="上传视频地址" prop="video" v-if="dataForm.video !== ''">
      <span>{{dataForm.video}}</span>
    </el-form-item>
    <el-form-item label="快乐咨询内容" prop="newContent">
      <!-- <UEditor ref="ueditor" id='newsinfo'></UEditor> -->
      <UE :config=config ref="ue"></UE>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import UEditor from '@/components/ueditor/ueditor.vue'
  import UE from '@/components/ue/ue.vue'
// import { watch } from 'fs';
  export default {
    data () {
      return {
        config: {
          autoHeightEnabled: true,
          autoFloatEnabled: false,
          initialContent: '请输入内容',
          autoClearinitialContent: true,
          initialFrameWidth: null,
          initialFrameHeight: 550,
          BaseUrl: '',
          UEDITOR_HOME_URL: '2001112897/static/ueditor/',
          serverUrl: this.$http.adornUrl(`/ueditor/exec?token=${this.$cookie.get('token')}`)
        },
        hideUpload: false,
        limitCount: 1,
        visible: false,
        isDisabled: false,
        dialogImageUrl: '',
        dialogVisible: false,
        videoFlag: false,
        videoUploadPercent: '0%',
        dialogFormVisible: false,
        key: [],
        dataForm: {
          newsId: 0,
          title: '',
          newsClassKey: '',
          keywords: '',
          contentType: '',
          content: '',
          newContent: '',
          newsFrom: '',
          likeNumber: 0,
          readingNumber: 0,
          forwardingNumber: 0,
          collectionNumber: 0,
          commentsNumber: 0,
          createTime: '',
          newsRemark: '',
          titleImage: [],
          fileType: 0,
          video: '',
          newType: 0
        },
        dataRule: {
          keywords: [
            { required: true, message: '咨询关键词(首页展示的)不能为空', trigger: 'blur' }
          ],
          title: [
            { required: true, message: '快乐咨询标题不能为空', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '快乐咨询内容不能为空', trigger: 'blur' }
          ],
          titleImage: [
            { required: true, message: '列表文章标题图片不能为空', trigger: 'blur' }
          ],
          newsFrom: [
            { required: true, message: '当前咨询来自哪个网站不能为空', trigger: 'blur' }
          ],
          likeNumber: [
            { required: true, message: '点赞数量不能为空', trigger: 'blur' },
            {pattern: /^\+?[0-9]\d*$/, message: '点赞数量为正整数', trigger: 'blur'}
          ],
          readingNumber: [
            { required: true, message: '阅读数量不能为空', trigger: 'blur' },
            {pattern: /^\+?[0-9]\d*$/, message: '阅读数量为正整数', trigger: 'blur'}
          ],
          forwardingNumber: [
            { required: true, message: '转发数量不能为空', trigger: 'blur' },
            {pattern: /^\+?[0-9]\d*$/, message: '转发数量为正整数', trigger: 'blur'}
          ],
          collectionNumber: [
            { required: true, message: '收藏数量不能为空', trigger: 'blur' },
            {pattern: /^\+?[0-9]\d*$/, message: '收藏数量为正整数', trigger: 'blur'}
          ],
          commentsNumber: [
            { required: true, message: '评论数量不能为空', trigger: 'blur' },
            {pattern: /^\+?[0-9]\d*$/, message: '评论数量为正整数', trigger: 'blur'}
          ],
          createTime: [
            { required: true, message: '创建时间不能为空', trigger: 'blur' }
          ]
          // newsRemark: [
          //   { required: true, message: '创建快乐咨询时候的备注不能为空', trigger: 'blur' }
          // ],
          // newContent: [
          //   { required: true, message: '不能为空', trigger: 'blur' }
          // ]
        }
      }
    },
    components: {
      UEditor,
      UE
    },
    watch: {
      'dataForm.content': function (val) {
        if (val.indexOf('mp.weixin.qq') !== -1) {
          this.$message('您填入的微信公众号地址，请将内容信息复制到富文本框中！')
          return false
        }
      }
    },
    methods: {
      // getUEContent () {
      //   let content = this.$refs.ue.getUEContent()
      //   console.log(content)
      // },
      // 图片预览
      handlePreview (file) {
        // debugger
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.titleImage.push({name: 'tu', url: res.data})
        }
        // console.log(this.dataForm.img)
      },
      // 删除文件之前的钩子函数
      handleRemove (file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        for (var i = 0; i < this.dataForm.titleImage.length; i++) {
          var picc = this.dataForm.titleImage[i]
          if (picc.url === file.url) {
            this.dataForm.titleImage.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 6000
        })
      },
      // 视频上传之前判断他的大小
      beforeUploadVideo (file) {
        const isLt10M = file.size / 1024 / 1024 < 2000
        if (!isLt10M) {
          this.$message.error('上传视频大小不能超过2000MB哦!')
          return false
        }
      },
      // 视频上传的时候获取上传进度传给进度条
      uploadVideoProcess (event, file, fileList) {
        this.videoFlag = true
        this.videoUploadPercent = parseInt(file.percentage)
      },
      // 视频上传成功之后返回视频地址
      handleVideoSuccess (res, file) {
        this.videoFlag = false
        this.videoUploadPercent = 0
        this.dataForm.video = res.data
      },
      init (id) {
        this.hideUpload = false
        this.dataForm.newsId = id || 0
        this.visible = true
        this.isDisabled = false
        this.dataForm.titleImage = []
        this.dataForm.title = ''
        this.dataForm.newsClassKey = ''
        this.dataForm.keywords = ''
        this.dataForm.contentType = ''
        this.dataForm.content = ''
        this.dataForm.newContent = ''
        this.dataForm.newsFrom = null
        this.dataForm.likeNumber = 0
        this.dataForm.readingNumber = 0
        this.dataForm.forwardingNumber = 0
        this.dataForm.collectionNumber = 0
        this.dataForm.commentsNumber = 0
        this.dataForm.createTime = ''
        this.dataForm.newsRemark = ''
        this.dataForm.fileType = 0
        this.dataForm.video = ''
        this.dataForm.newType = 0
        // this.ueGetContent()
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.newsId === 0) {
            this.$http({
              url: this.$http.adornUrl('/newInfo/queryClass'),
              method: 'post',
              data: this.$http.adornData()
            }).then(({data}) => {
              this.key = data.data
              this.ueSetContent('')
            })
          }
          if (this.dataForm.newsId) {
            this.$http({
              url: this.$http.adornUrl(`/newInfo/getNewInfoDetailsByNewsId/${this.dataForm.newsId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.newsId = data.data.newsId
                this.dataForm.keywords = data.data.keywords
                this.dataForm.title = data.data.title
                this.dataForm.content = data.data.content
                // this.dataForm.titleImage = data.data.titleImage
                var pic = data.data.titleImage
                // if (pic.indexOf('.jpg') !== -1 || pic.indexOf('.png') !== -1 || pic.indexOf('.jpeg') !== -1) {
                //   this.dataForm.fileType = 1
                //   this.dataForm.titleImage.push({name: 'tu', url: 'https://image.yilianbaihui.cn/consumer/news_info/' + pic})
                // }
                // if (pic.indexOf('.avi') !== -1 || pic.indexOf('.rmvb') !== -1 || pic.indexOf('.rm') !== -1 || pic.indexOf('.asf') !== -1 || pic.indexOf('.divx') !== -1 || pic.indexOf('.mpg') !== -1 || pic.indexOf('.mpeg') !== -1 || pic.indexOf('.mpe') !== -1 || pic.indexOf('.wmv') !== -1 || pic.indexOf('.mp4') !== -1 || pic.indexOf('.mkv') !== -1 || pic.indexOf('.vob') !== -1) {
                //   this.dataForm.fileType = 2
                //   this.dataForm.video = 'https://image.yilianbaihui.cn/consumer/video/' + pic
                // }
                this.dataForm.titleImage.push({name: 'tu', url: 'https://image.yilianbaihui.cn/consumer/news_info/' + pic})
                this.dataForm.newsFrom = data.data.newsFrom
                this.dataForm.newsFromUrl = data.data.newsFromUrl
                this.dataForm.newsClassKey = data.data.newsClassKey
                this.dataForm.isRecommend = data.data.isRecommend
                this.dataForm.recommendSort = data.data.recommendSort
                this.dataForm.likeNumber = data.data.likeNumber
                this.dataForm.readingNumber = data.data.readingNumber
                this.dataForm.forwardingNumber = data.data.forwardingNumber
                this.dataForm.collectionNumber = data.data.collectionNumber
                this.dataForm.commentsNumber = data.data.commentsNumber
                this.dataForm.createUserId = data.data.createUserId
                this.dataForm.createUserType = data.data.createUserType
                this.dataForm.createTime = data.data.createTime
                this.dataForm.updateUserId = data.data.updateUserId
                this.dataForm.updateTime = data.data.updateTime
                this.dataForm.auditStatus = data.data.auditStatus
                this.dataForm.auditRemark = data.data.auditRemark
                this.dataForm.newsRemark = data.data.newsRemark
                this.dataForm.state = data.data.state
                // this.$refs.ueditor.setUEContent(data.data.newContent)
                this.ueSetContent(data.data.newContent)
                this.dataForm.contentType = data.data.contentType
              }
              this.hideUpload = true
            })
          }
        })
      },
      // 获取文档内容
      ueGetContent: function () {
        return this.$refs.ue.getUEContent()
      },
      ueSetContent: function (content) {
        this.$refs.ue.setUEContent(content)
      },
      // 表单提交
      dataFormSubmit () {
        if (this.dataForm.content.indexOf('mp.weixin.qq.com') !== -1) {
          // if (this.$refs.ueditor.getUEContent() === null || this.$refs.ueditor.getUEContent() === '') {
          //   this.$message('您填入的微信公众号地址，请将内容信息复制到富文本框中！')
          //   return false
          // }
          if (this.ueGetContent() === null || this.ueGetContent() === '') {
            this.$message('您填入的微信公众号地址，请将内容信息复制到富文本框中！')
            return false
          }
        }
        if (this.dataForm.titleImage.length <= 0) {
          this.$message('请上传图片文件！')
          return false
        }
        console.log(this.dataForm.titleImage)
        // let titleimage = ''
        // if (this.dataForm.titleImage.length > 0) {
        //   titleimage = this.dataForm.titleImage.url.substring(this.dataForm.titleImage.url.lastIndexOf('/') + 1, this.dataForm.titleImage.url.length)
        // }
        // if (this.dataForm.video !== '') {
        //   titleimage = this.dataForm.newsClassKey + '/' + this.dataForm.video.substring(this.dataForm.video.lastIndexOf('/') + 1, this.dataForm.video.length)
        // }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.isDisabled = true
            this.dataForm.newContent = this.ueGetContent()
            this.$http({
              url: this.$http.adornUrl(`/newInfo/${!this.dataForm.newsId ? 'addNewsInfo' : 'modifyNewInfoDetailsByNewsId'}`),
              method: 'post',
              data: this.$http.adornData({
                'newsId': this.dataForm.newsId || undefined,
                'keywords': this.dataForm.keywords,
                'title': this.dataForm.title,
                'content': this.dataForm.content,
                'titleImage': this.dataForm.titleImage,
                'newsFrom': this.dataForm.newsFrom,
                'newsClassKey': this.dataForm.newsClassKey,
                'newsRemark': this.dataForm.newsRemark,
                'contentType': this.dataForm.contentType,
                'likeNumber': this.dataForm.likeNumber,
                'readingNumber': this.dataForm.readingNumber,
                'forwardingNumber': this.dataForm.forwardingNumber,
                'collectionNumber': this.dataForm.collectionNumber,
                'commentsNumber': this.dataForm.commentsNumber,
                'createTime': this.dataForm.createTime,
                'newContent': this.dataForm.newContent
                // 'newContent': this.$refs.ueditor.getUEContent()
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
<style>
  .hide .el-upload--picture-card {  display: none; }
</style>
